using System;
using System.Text;
using Cairo;

namespace fuzzyKittenVNC
{
	public class HTML5_Base64Renderer : VNCGenericRenderer
	{
		private Random rnd = new Random();	
		public HTML5_Base64Renderer (VNCClient fb) : base(fb) {
			
		}
		
		public override void renderDirtyRegions() {
			VNCClientFramebuffer framebuffer = VNCClientFramebuffer.getInstanceForClient(this.fb);
			foreach(VNCClientFramebuffer.Region region in framebuffer.dirtyRegions) {
				this.render(region.x,region.y,region.w,region.h);
			}
			framebuffer.dirtyRegions.Clear();
		}
		public override void render(uint x, uint y, uint width, uint height) {
			VNCClientFramebuffer framebuffer = VNCClientFramebuffer.getInstanceForClient(this.fb);
			string baseFrame = "[{{ \"type\": \"FU\", \"x\":{0}, \"y\":{1}, \"width\":{2}, \"height\":{3}, \"data\":\"{4}\" }}]";	
		
			byte[] frameBufferSlice = framebuffer.getArea(x,y,width, height);			
			byte[] png = getPNG(width,height,framebuffer,frameBufferSlice);

			// JSONify
			string data = String.Format(baseFrame,x,y,width,height,Convert.ToBase64String(png));
			this.sendDelegate(Encoding.ASCII.GetBytes(data));
		}
		
		public byte[] getPNG(uint width, uint height, VNCClientFramebuffer framebuffer,byte[] pixel) {
			try {
				string tmp = String.Format("tmp_{0}.vnc",rnd.Next(100000,999999));
				using (Cairo.ImageSurface draw = new Cairo.ImageSurface(pixel,Cairo.Format.Argb32,(int) width,(int) height,(int) width*(int)(framebuffer.format.pixFormat.bits_per_pixel/8))) {
					draw.WriteToPng(tmp);
				};
	
				byte[] png;
				
				png = System.IO.File.ReadAllBytes(tmp);
				System.IO.File.Delete(tmp);
				return png;
			} catch(Exception e) {
				Console.WriteLine(e);
				return null;
			}
		}
	}
}

